package model.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Observable;

import model.cache.CacheController;

public class Server extends Observable {
	public class ClientListenerThread extends Thread {
		public void run() {
			while (run) {
				try {
					setChanged();
					notifyObservers("Listening for incoming clients on "+socket.getInetAddress()+".");
					Socket client = socket.accept();
					new ClientHandler(client, cacheController).start();
					setChanged();
					notifyObservers("Handling client request from "+client.getInetAddress()+".");
				} catch (SocketException e) {
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private ServerSocket socket;

	private CacheController cacheController;

	private boolean run;

	public Server(CacheController cacheController) {
		this.cacheController = cacheController;
	}

	public void exit() {
		this.run = false;
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void start() {
		this.run = true;
		try {
			socket = new ServerSocket(20000);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		new ClientListenerThread().start();
	}
}
